using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using HalalCheck.Droid.ServiceDepedency;
using HalalCheck.Utils;
using Xamarin.Forms;

[assembly: Dependency(typeof(ImageServices))]
namespace HalalCheck.Droid.ServiceDepedency
{
    public class ImageServices : IImageServices
    {
        public async Task<byte[]> CompressImage(byte[] input, int quality)
        {
            var options = new BitmapFactory.Options
            {
                InJustDecodeBounds = false,
                InPurgeable = true,
                InInputShareable = true,
                InSampleSize = 4
            };

            using (var bp = BitmapFactory.DecodeByteArray(input, 0, input.Length, options))
            {
                var output = await bp.ToByteArray(quality);

                return output;
            }
        }
    }

    public static class BitmapHelpers
    {
        public static async Task<byte[]> ToByteArray(this Bitmap bp, int quality)
        {
            if (bp == null) return null;

            using (var stream = new MemoryStream())
            {
                await bp.CompressAsync(Bitmap.CompressFormat.Jpeg, (quality == -1 ? 100 : quality), stream);

                return stream.ToArray();
            }
        }
    }
}